/**
 * Copyright (C) 2013 Fabien Fleurey <fabien@fleurey.com>
 */
package com.fleurey.android.light;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.Toast;

import com.fleurey.android.light.backgroundmanager.LightService;
import com.fleurey.android.light.flashmanager.FlashManager;

import java.util.List;

public class MainActivity extends Activity {

	private ImageButton mImageButton;

	public static boolean isServiceExisted(Context context, String className) {
		ActivityManager activityManager = (ActivityManager) context
				.getSystemService(Context.ACTIVITY_SERVICE);
		List<ActivityManager.RunningServiceInfo> serviceList = activityManager
				.getRunningServices(Integer.MAX_VALUE);

		for (ActivityManager.RunningServiceInfo serviceInfo : serviceList) {
			if (serviceInfo.service.getClassName().equals(className)) {
				return true;
			}
		}
		return false;
	}
	
	private BroadcastReceiver mReceiver = new BroadcastReceiver() {
	    @Override
	    public void onReceive(Context context, Intent intent) {
	        if(LightService.ACTION_SERVICE_STOPPED.equals(intent.getAction())) {
	        	mImageButton.setBackgroundResource(R.drawable.img_background_off);
	        }
			if(LightService.ACTION_SERVICE_STARTED.equals(intent.getAction())) {
				mImageButton.setBackgroundResource(R.drawable.img_background_on);
			}
	    }
	};
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		mImageButton = (ImageButton) findViewById(R.id.button);
		mImageButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (isServiceExisted(getApplicationContext(), LightService.class.getName())) {
					stopService(new Intent(getApplicationContext(), LightService.class));
				} else {
					startService(new Intent(getApplicationContext(), LightService.class));
				}
			}
		});
	}
	
	@Override
	protected void onResume() {
		super.onResume();

		IntentFilter ift=new IntentFilter(LightService.ACTION_SERVICE_STOPPED);
		ift.addAction(LightService.ACTION_SERVICE_STARTED);
		registerReceiver(mReceiver,ift);

		if (!FlashManager.isFlashAvailable(getApplicationContext())) {
			Toast.makeText(getApplicationContext(), R.string.no_flash, Toast.LENGTH_LONG).show();
			finishAffinity();
			return;
		}

		startService(new Intent(getApplicationContext(), LightService.class));
	}

	@Override
	protected void onPause() {
		super.onPause();
		unregisterReceiver(mReceiver);
	}


}
